﻿
Imports std
Imports storoomc

Public Module readall
    Private Sub help()
        raiseError("usage, readall.exe [host] [port]")
    End Sub

    Private Sub read(ByVal talk2 As storoomTalk2, ByVal l As vector(Of String), _
                     ByVal start As Int64, ByVal [end] As Int64)
        For i As Int64 = start To [end] - 1
            assert(talk2.read(l(i)))
        Next
        If talk2.issue() Then
            For i As Int64 = 0 To [end] - start - 1
                Dim rst As Boolean = False
                Dim buff As bytes = Nothing
                assert(talk2.result(i, rst, buff))
                If Not rst Then
                    raiseError("cannot read ", l(start + i))
                Else
                    'write to file for perf concern
                    writefile(combinepath(filesystem.temppath(), "temp"), encoding.utf8().GetString(+buff))
                End If
            Next
        Else
            raiseError("cannot issue request to server ", displayHostPort(talk2.host(), talk2.port()))
        End If
    End Sub

    Private Sub readall(ByVal host As String, ByVal port As Int32)
        Dim talk As storoomTalk = Nothing
        talk = New storoomTalk(host, port)
        Dim l As vector(Of String) = Nothing
        If Not talk.list(l) Then
            raiseError("cannot get list from ", displayHostPort(host, port))
        Else
            Dim talk2 As storoomTalk2 = Nothing
            talk2 = New storoomTalk2(host, port)
            Const eachround As Int64 = 100
            Dim i As Int64
            For i = 0 To l.size() - 1 Step eachround
                read(talk2, l, i, min(l.size(), i + eachround))
            Next
            If i < l.size() Then
                read(talk2, l, i, l.size())
            End If
        End If
    End Sub

    Public Sub main(ByVal args() As String)
        debugpause()
        startmain(Nothing, errorHandle.NOLOGFILEMARK)
        counter.initial(counter.NOCOUNTERFILEMARK)
        Dim host As String = Nothing
        Dim port As Int32 = 0
        If args.Length() < 2 Then
            help()
        Else
            host = args(0)
            If Not convertor.toint32(args(1), port) Then
                help()
            Else
                readall(host, port)
            End If
        End If
        finishmain()
    End Sub
End Module
